package com.xujichang.viewbinding

import android.util.Log
import android.view.LayoutInflater
import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import kotlin.reflect.KClass

inline fun <reified VB : ViewBinding> ComponentActivity.viewBindings(): Lazy<VB> =
    ViewBindingLazy(VB::class, this)

class ViewBindingLazy<VB : ViewBinding>(
    private val viewBindingClass: KClass<VB>,
    private val activity: ComponentActivity
) : Lazy<VB>, LifecycleEventObserver {
    @Volatile
    private var _value: VB? = null

    init {
        activity.lifecycle.addObserver(this)
    }

    override val value: VB
        get() {
            val viewBinding = _value
            return if (null == viewBinding) {
                val method =
                    viewBindingClass.java.getMethod("inflate", LayoutInflater::class.java)
                (method.invoke(null, activity.layoutInflater) as VB).also {
                    _value = it
                }
            } else {
                viewBinding
            }
        }

    override fun isInitialized(): Boolean = _value != null

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> doCreate()
            Lifecycle.Event.ON_DESTROY -> doDestroy()
            Lifecycle.Event.ON_ANY -> {

            }
            else -> {

            }
        }
    }

    private fun doDestroy() {
        _value = null
    }

    private fun doCreate() {

    }
}